package com.key.win.business.chat.ctrl;

import com.key.win.base.auth.AuthenticationUtil;
import com.key.win.base.exception.BizException;
import com.key.win.base.util.DateUtils;
import com.key.win.base.web.PageRequest;
import com.key.win.base.web.PageResult;
import com.key.win.base.web.Result;
import com.key.win.business.chat.eums.ImMessageContentTypeEnum;
import com.key.win.business.chat.model.ImApply;
import com.key.win.business.chat.service.ImApplyDetailService;
import com.key.win.business.chat.service.ImApplyService;
import com.key.win.business.chat.vo.ImApplyVo;
import com.key.win.business.chat.vo.ImSystemMessageOutVo;
import com.key.win.business.chat.vo.ImUserVo;
import com.key.win.common.log.annotation.LogAnnotation;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/apply/*")
@Api("好友相关的api")
public class ImApplyCtrl {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private ImApplyService imApplyService;

    @Autowired
    private ImApplyDetailService imApplyDetailService;


    @PostMapping("/findApplyByPaged")
    @ApiOperation(value = "Apply分页")
    @LogAnnotation(module = "im", recordRequestParam = false)
    public PageResult<ImApply> findApplyByPaged(@RequestBody PageRequest<ImApply> pageRequest) {
        return imApplyService.findApplyByPaged(pageRequest);
    }

    @PostMapping("/findApply")
    @ApiOperation(value = "Apply List")
    @LogAnnotation(module = "im", recordRequestParam = false)
    public Result<List<ImApply>> findApply(@RequestBody ImApply imApply) {
        return Result.succeed(imApplyService.findApply(imApply));
    }

    @GetMapping("/get/{id}")
    @ApiOperation(value = "获取Apply")
    @LogAnnotation(module = "im", recordRequestParam = false)
    public Result get(@PathVariable String id) {
        return Result.succeed(imApplyService.getById(id));
    }

    @GetMapping("/get/full/{id}")
    @ApiOperation(value = "获取Apply")
    @LogAnnotation(module = "im", recordRequestParam = false)
    public Result getFull(@PathVariable String id) {
        return Result.succeed(imApplyService.getImApplyFull(id));
    }

    @DeleteMapping("/delete/{id}")
    @ApiOperation(value = "删除")
    @LogAnnotation(module = "im", recordRequestParam = true)
    public Result delete(@PathVariable String id) {
        if (imApplyDetailService.deleteApplyDetailByApplyId(id)) {
            return Result.result(imApplyService.removeById(id));
        }
        return Result.result(false);
    }

    @PostMapping("/addApply")
    @ApiOperation(value = "申请添加好")
    @LogAnnotation(module = "im", recordRequestParam = true)
    public Result addApply(@RequestBody ImApply imApply) {
        if (imApply.getUserId().equals(imApply.getTargetId())) {
            logger.error("不能添加自己为好友！");
            throw new BizException("不能添加自己为好友！");
        }
        imApply.setUserId(AuthenticationUtil.getUserId());
        return Result.result(imApplyService.saveOrUpdateApply(imApply));
    }

    @PostMapping("/approve/{id}/{status}")
    @ApiOperation(value = "好友审批[1:同意，其它都为拒绝]")
    @LogAnnotation(module = "im", recordRequestParam = true)
    public Result approve(@PathVariable String id, @PathVariable int status) {
        ImApply apply = imApplyService.getById(id);
        if (apply.getResult() != null) {
            logger.info("已{}用户[{}]的好友申请", apply.getResult() ? "同意" : "拒绝", apply.getUserId());
            throw new BizException("已" + (apply.getResult() ? "同意" : "拒绝") + "好友的申请！");
        }
        if (status == 1) {
            apply.setResult(true);
        } else {
            apply.setResult(false);
        }
        return Result.result(imApplyService.approve(apply));
    }

    @PostMapping("/findApplyDetail")
    @ApiOperation(value = "获取申请详情")
    @LogAnnotation(module = "im", recordRequestParam = true)
    public Result<List<ImApplyVo>> findApplyDetail() {
        List<ImApplyVo> applyDetails = imApplyService.findApplyDetail();
        List<ImSystemMessageOutVo> imSystemMessageOutVos = new ArrayList<>();
        if (!CollectionUtils.isEmpty(applyDetails)) {
            for (ImApplyVo imApplyVo : applyDetails) {
                ImSystemMessageOutVo imSystemMessageOutVo = new ImSystemMessageOutVo();
                imSystemMessageOutVo.setMessage(imApplyVo.getDesc());
                imSystemMessageOutVo.setTimestamp(DateUtils.dateTimeToStr(imApplyVo.getCreateDate()));
                ImUserVo formUser = new ImUserVo();
                formUser.setNickName(imApplyVo.getFromUserNickName());
                formUser.setId(imApplyVo.getUserId());
                formUser.setAvatar(imApplyVo.getFromUserAvatar());
                imSystemMessageOutVo.setFromUser(formUser);
                ImUserVo toUser = new ImUserVo();
                toUser.setNickName(imApplyVo.getToUserNickName());
                toUser.setId(imApplyVo.getToUserId());
                toUser.setAvatar(imApplyVo.getToUserAvatar());
                imSystemMessageOutVo.setToUser(toUser);
                imSystemMessageOutVo.setContentType(ImMessageContentTypeEnum.TEXT.name());
                imSystemMessageOutVos.add(imSystemMessageOutVo);
            }
        }
        return Result.succeed(applyDetails);
    }
}
